package com.ys.controller.web.business;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ys.service.sys.UploadService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MyConfig;
import com.ys.entity.business.TpAmazonShopProduct;
import com.ys.entity.business.TpAmazonShopProductCount;
import com.ys.service.business.TpAmazonAnalysisService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;

@Controller
@RequestMapping("/web/business/tpAmazonAnalysis")
public class WebTpAmazonAnalysisController {
	private static final Logger logger = LoggerFactory.getLogger(WebTpAmazonAnalysisController.class);

	private static Long MENU_ID = 45L;

	@Autowired
	private CommonApiService<TpAmazonShopProduct> commonApiService;
	@Autowired
	private TpAmazonAnalysisService tpAmazonAnalysisService;

	/*
	获取结果集
	 */
	public LayuiTableVoJA getResult(TpAmazonShopProduct cond) {
		//获取昨天的日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		String agoDay = sdf.format(calendar.getTime());

		cond.addField("B.VGsBm AS vGsBm");
		cond.addField("B.UserId AS userId");
		cond.addField(
						"B.ProductName AS name," + //商品名称
						"B.VGsJc AS companyName," + //运营公司简称
						"B.ShopName AS shopName," + //店铺名
						"B.UserName AS userName" //运营人
		);

		//cond.addLeftJoin("TP_AmazonShopProductCount B ON A.Guid = B.ShopProductGuid");
		cond.addLeftJoin("(SELECT MAX(C.ProductName) AS ProductName,MAX(C.VGsBm) AS VGsBm,MAX(C.UserId) AS UserId," +
				"MAX(C.VGsJc) AS VGsJc,MAX(C.ShopName) AS ShopName,MAX(C.UserName) AS UserName,C.ShopProductGuid " +
				" FROM kjecp_amazonproduct.dbo.TP_AmazonShopProductCount C Where C.InfoTime = '"+agoDay+"' GROUP BY C.ShopProductGuid) B ON A.Guid = B.ShopProductGuid");
		//商品表code非空过滤
		cond.where("A.code IS NOT NULL AND A.countIsShow = 1");
		//cond.where("B.InfoTime = '"+agoDay+"'");
		//排序
		//cond.setOrderby("A.ShopGuid");
		cond.setOrderby("A.SellerSku");
		//权限
		cond = commonApiService.dataAuth(MENU_ID, cond);
		//获取数据
		LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
		JSONArray tableVoJAData = tableVoJA.getData();
		//转换
		List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
		//处理数据
		resList = setList(resList);
		JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resList));
		tableVoJA.setData(jsonArray);
		return tableVoJA;
	}


	//处理返回的数据
	public List setList(List<Map> resDate){
		List<HashMap<String, String>> dateList = getAgoDay();//过去30天日期集合
		List<HashMap<String, String>> tableDate = new ArrayList();

		String shopProductId = null;
		String shopGuid = null;
		List<String> shopCodeList = new ArrayList();
		for( Map resMap:resDate ){
			if(resMap.get("guid")!=null && !resMap.get("guid").equals("")){
				if(shopProductId == null || shopProductId.equals("")){
					shopProductId = "'"+ resMap.get("guid") + "'";
				}else {
					shopProductId = shopProductId + ",'"+ resMap.get("guid") + "'";
				}
			}
			if(resMap.get("shopGuid")!=null && !resMap.get("shopGuid").equals("")){
				if(shopGuid == null || shopGuid.equals("")){
					shopGuid = "'"+ resMap.get("shopGuid") + "'";
				}else {
					shopGuid = shopGuid + ",'"+ resMap.get("shopGuid") + "'";
				}
			}
			if(resMap.get("code")!=null && !resMap.get("code").equals("")){
				shopCodeList.add(resMap.get("code").toString());
			}
		}

		//获取近30天数据
		List<TpAmazonShopProductCount> countList = new TpAmazonShopProductCount()
				.where("A.ShopProductGuid IN ( "+ shopProductId +" )")
				.where("A.InfoTime between '"+ dateList.get(0).get("dateTime") +"' and '" + dateList.get(dateList.size()-1).get("dateTime")+"'")
				.setOrderby("A.ShopProductGuid")
				.queryList();


		resDate.forEach(thisDate->{
			//亚马逊库存数量
			Object fulfillableQuantityObject = thisDate.get("fulfillableQuantity");
			float fulfillableQuantity = (fulfillableQuantityObject!=null && !fulfillableQuantityObject.equals("")?Float.parseFloat(fulfillableQuantityObject.toString()):0);
			//在途库存数量
			Object inboundObject = thisDate.get("inboundWorkingQuantity");
			float inboundNum = (inboundObject!=null && !inboundObject.equals("")?Float.parseFloat(inboundObject.toString()):0);
			Object reservedObject = thisDate.get("reservedQuantity");
			float reservedNum = (reservedObject!=null && !reservedObject.equals("")?Float.parseFloat(reservedObject.toString()):0);
			float wayNum = inboundNum + reservedNum; //在途库存=入库数量+预留数量
			//float wayNum = inboundNum; //在途库存=入库数量


			thisDate.put("name",thisDate.get("name"));//商品名称
			thisDate.put("companyName",thisDate.get("companyName"));//运营公司简称
			thisDate.put("userName",thisDate.get("userName"));//运营人
			thisDate.put("shopName",thisDate.get("shopName")); //店铺名
			thisDate.put("fulfillableQuantity",(int) fulfillableQuantity);
			//thisDate.put("inboundWorkingQuantity",(int) inboundWorkingQuantity);
			thisDate.put("buyWinProbability",thisDate.get("recommendPrice")!=null?String.format("%.0f", Float.parseFloat(thisDate.get("recommendPrice").toString()))+"%":"0%");
			thisDate.put("changeProbability",thisDate.get("commoditySession")!=null?String.format("%.0f", Float.parseFloat(thisDate.get("commoditySession").toString()))+"%":"0%");


			//String buyWinProbability = "0";//购买赢得率
			//String changeProbability = "0";//转换率
			String  ninetyMonthCount = "0";//统计90天的月销量
			String  thirtyMonthCount = "0";//统计30天的月销量

			//根据Guid过滤TP_AmazonShopProductCount表数据
			List<TpAmazonShopProductCount> infoList = countList.stream()
					.filter( infoItem -> infoItem.getShopProductGuid().equals(thisDate.get("guid")) )
					.collect(Collectors.toList());

			if(infoList!=null && infoList.size()>0){
				for(int z=0;z<4;z++){
					HashMap<String, String> newThisDate = new HashMap<>();
					String itemStr = "";
					if(z == 0){
						itemStr = "排名";
					}else if(z == 1){
						itemStr = "售价";
					}else if(z == 2){
						itemStr = "数量";
					}else {
						itemStr = "访问量";
					}
					newThisDate.put("itemStr",itemStr);

					for(int j=0;j<dateList.size();j++){

						String countNum = "";
						String thisDateTime = dateList.get(j).get("dateTime");
						String thisDateNum = dateList.get(j).get("dateNum");

						for( TpAmazonShopProductCount countItem : infoList){

							Map infoMap = JSONObject.parseObject(countItem.getInfo(), Map.class);
							if(z == 0){
								countNum = infoMap.get("rank")==null?"":infoMap.get("rank").toString();
							}else if(z == 1){
								countNum = infoMap.get("price")==null?"":infoMap.get("price").toString();
							}else if(z == 2){
								countNum = infoMap.get("count")==null?"":infoMap.get("count").toString();
							}else {
								countNum = infoMap.get("visit")==null?"":infoMap.get("visit").toString();
							}
							if(thisDateTime.equals(countItem.getInfoTime())){
								//flag++;
								newThisDate.put(thisDateNum,countNum);

								//获取最新一天的数据
								if(j==dateList.size()-1){
									ninetyMonthCount = infoMap.get("ninetyMonthCount")==null?"":infoMap.get("ninetyMonthCount").toString();//统计90天的月销量
									thirtyMonthCount = infoMap.get("thirtyMonthCount")==null?"":infoMap.get("thirtyMonthCount").toString();//统计30天的月销量

									newThisDate.put("ninetyMonthCount",String.format("%.0f", Float.parseFloat(ninetyMonthCount)));
									newThisDate.put("thirtyMonthCount",String.format("%.0f", Float.parseFloat(thirtyMonthCount)));

									//30天月销量
									float monthCount = (thirtyMonthCount!=null && !thirtyMonthCount.equals("")?Float.parseFloat(thirtyMonthCount):0);//月销量
									//90天月销量
									float monthCountNinety = (ninetyMonthCount!=null && !ninetyMonthCount.equals("")?Float.parseFloat(ninetyMonthCount):0);//月销量

									String inboundWorkingQuantityStr = infoMap.get("inboundWorkingQuantity")==null?"0":infoMap.get("inboundWorkingQuantity").toString();
									String noStorageCountStr = infoMap.get("noStorageCount")==null?"0":infoMap.get("noStorageCount").toString();
									float inboundWorkingQuantity = Float.parseFloat(inboundWorkingQuantityStr);
									float noStorageCount = Float.parseFloat(noStorageCountStr);

									//30天亚马逊系数
									String amazonCount = (monthCount!=0?String.format("%.1f", fulfillableQuantity / monthCount):"0.0");
									//30天在途系数
									String wayCount = (monthCount!=0?String.format("%.1f", (fulfillableQuantity + wayNum) / monthCount):"0.0");
									//30天仓库系数
									String boundCount = (monthCount!=0?String.format("%.1f", (fulfillableQuantity + wayNum + inboundWorkingQuantity) / monthCount):"0.0");
									//30天采购库存系数
									String noStorageCountThirty = (monthCount!=0?String.format("%.1f", (fulfillableQuantity + wayNum + inboundWorkingQuantity + noStorageCount) / monthCount):"0.0");

									//90天亚马逊系数
									String amazonCountNinety = (monthCountNinety!=0?String.format("%.1f", fulfillableQuantity / monthCountNinety):"0.0");
									//90天在途系数
									String wayCountNinety = (monthCountNinety!=0?String.format("%.1f", (fulfillableQuantity + wayNum) / monthCountNinety):"0.0");
									//90天仓库系数
									String boundCountNinety = (monthCountNinety!=0?String.format("%.1f", (fulfillableQuantity + wayNum + inboundWorkingQuantity) / monthCountNinety):"0.0");
									//90天采购库存系数
									String noStorageCountNinety = (monthCountNinety!=0?String.format("%.1f", (fulfillableQuantity + wayNum + inboundWorkingQuantity + noStorageCount) / monthCountNinety):"0.0");

									newThisDate.put("wayNum",((int) wayNum)+"");
									newThisDate.put("noStorageCount",((int) noStorageCount)+"");
									newThisDate.put("amazonCountThirty",amazonCount);
									newThisDate.put("wayCountThirty",wayCount);
									newThisDate.put("boundCountThirty",boundCount);
									newThisDate.put("noStorageCountThirty",noStorageCountThirty);
									newThisDate.put("amazonCountNinety",amazonCountNinety);
									newThisDate.put("wayCountNinety",wayCountNinety);
									newThisDate.put("boundCountNinety",boundCountNinety);
									newThisDate.put("noStorageCountNinety",noStorageCountNinety);
									newThisDate.put("inboundWorkingQuantityCount",((int) inboundWorkingQuantity)+"");
								}
							}
						}

					}
					newThisDate.putAll(thisDate);
					tableDate.add(newThisDate);

				}
			}else {
				for(int z=0;z<4;z++) {
					HashMap<String, String> newThisDate = new HashMap<>();
					String itemStr = "";
					if (z == 0) {
						itemStr = "排名";
					} else if (z == 1) {
						itemStr = "售价";
					} else if (z == 2) {
						itemStr = "数量";
					} else {
						itemStr = "访问量";
					}
					newThisDate.put("itemStr", itemStr);
					newThisDate.putAll(thisDate);
					tableDate.add(newThisDate);
				}
			}
		});
		return tableDate;
	}


	/*
	 * 获取运营跟踪菜单统计数据
	 */
    @RequiresPermissions("tpAmazonShopProductCount:view")
	@RequestMapping("/getAnalysisList")
	@ResponseBody
	public LayuiTableVoJA getAnalysisList(Model model, HttpServletRequest request, HttpServletResponse response,
										  @ModelAttribute TpAmazonShopProduct cond,
										  String conditions
	){
		return getResult(cond);
	}



	/*
	 * 导出
	 */
	@PostMapping("/toExport")
	@ResponseBody
	public LayuiTableVoJA exportExcel(Model model,@ModelAttribute TpAmazonShopProduct cond,HttpServletResponse response) throws Exception {
		//创建一个工作簿
		SXSSFWorkbook wb = new SXSSFWorkbook(100);
		Sheet sheet = wb.createSheet("Sheet1");

		Map<String,List<String>> headMsg = setheadMsg();
		List<String> headerMsg1 = headMsg.get("headerMsg1");//一级表头
		List<String> headerMsg2 = headMsg.get("headerMsg2");//二级表头
		// 创建表头行
		Row headerRow = sheet.createRow(0);
		for(int i=0;i<headerMsg1.size();i++){
			// 创建表头单元格
			Cell headerCell = headerRow.createCell(i);
			headerCell.setCellValue(headerMsg1.get(i));
		}
		// 创建表头行
		Row headerRow2 = sheet.createRow(1);
		for(int i=0;i<headerMsg2.size();i++){
			// 创建表头单元格
			Cell headerCell = headerRow2.createCell(i);
			headerCell.setCellValue(headerMsg2.get(i));
		}
		cond._ys_page = 99;
		//获取数据
		LayuiTableVoJA tableVoJA = getResult(cond);
		JSONArray tableVoJAData = tableVoJA.getData();
		//转换
		List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);

		List<String> cellList = setCellMsg();
		// 填充数据
		for (int i = 0; i < resList.size(); i++) {
			Map msg = resList.get(i);
			Row dataRow = sheet.createRow(i + 2);
			for(int j = 0; j < cellList.size(); j++) {
				Cell dataCell = dataRow.createCell(j);
				String cellMsg = cellList.get(j);
				if(msg.get(cellMsg)!=null){
					dataCell.setCellValue(msg.get(cellMsg).toString());
				}
			}
		}

		// 合并单元格CellRangeAddress(起始行号，终止行号，起始列号，终止列号)
		//合并一级表头
		//合并行
		CellRangeAddress region0 = new CellRangeAddress(0, 0, 0, 2);//店铺信息
		sheet.addMergedRegion(region0);
		CellRangeAddress region1 = new CellRangeAddress(0, 0, 3, 8);//商品基础信息
		sheet.addMergedRegion(region1);
		CellRangeAddress region2 = new CellRangeAddress(0, 0, 9, 10);//商品运营信息
		sheet.addMergedRegion(region2);
		CellRangeAddress region3 = new CellRangeAddress(0, 0, 11, 13);//亚马逊库存
		sheet.addMergedRegion(region3);
		CellRangeAddress region4 = new CellRangeAddress(0, 0, 14, 16);//在途库存
		sheet.addMergedRegion(region4);
		CellRangeAddress region5 = new CellRangeAddress(0, 0, 17, 19);//仓储库存
		sheet.addMergedRegion(region5);
		CellRangeAddress region6 = new CellRangeAddress(0, 0, 20, 22);//采购库存
		sheet.addMergedRegion(region6);
		CellRangeAddress region7 = new CellRangeAddress(0, 0, 26, 55);//近30天运营数据
		sheet.addMergedRegion(region7);
		//合并列
		CellRangeAddress region8 = new CellRangeAddress(0, 1, 23, 23);//近30天月销量
		sheet.addMergedRegion(region8);
		CellRangeAddress region9 = new CellRangeAddress(0, 1, 24, 24);//近90天月销量
		sheet.addMergedRegion(region9);
		CellRangeAddress region10 = new CellRangeAddress(0, 1, 25, 25);//项目
		sheet.addMergedRegion(region10);
		//合并数据的列
		for (int i = 0; i < resList.size(); i=i+4) {
			for (int j = 0; j < 25; j++) {//25是近30天和项目列前面的列
				CellRangeAddress region = new CellRangeAddress(2+i, i+5, j, j);
				sheet.addMergedRegion(region);
			}
		}

		// 导出Excel文件
		String filePath = "运营跟踪数据_"+new Date().getTime()+".xlsx";
		String downloadPath = MyConfig.getProfile() + "/" + filePath;
		File file = new File(downloadPath);
		FileOutputStream fos = new FileOutputStream(file);
		wb.write(fos);
		fos.close();

		LayuiTableVoJA result = new LayuiTableVoJA();
		result.setCode(0);
		UploadService.UploadDto dto = commonApiService.uploadLocalToServer(downloadPath);
		//返回文件路径
		result.setMsg(dto.getUrl());

		return result;
	}

	//设置表的列信息
	public static List<String> setCellMsg() {
		List<String> cellMsg = new ArrayList<>();
		cellMsg.add("shopName");
		cellMsg.add("companyName");
		cellMsg.add("userName");
		cellMsg.add("mainImage");
		cellMsg.add("code");
		cellMsg.add("name");
		cellMsg.add("sellerSku");
		cellMsg.add("asin");
		cellMsg.add("fnSku");
		//cellMsg.add("comment");
		//cellMsg.add("score");
		cellMsg.add("buyWinProbability");
		cellMsg.add("changeProbability");
		cellMsg.add("fulfillableQuantity");
		cellMsg.add("amazonCountThirty");
		cellMsg.add("amazonCountNinety");
		cellMsg.add("wayNum");
		cellMsg.add("wayCountThirty");
		cellMsg.add("wayCountNinety");
		cellMsg.add("inboundWorkingQuantityCount");
		cellMsg.add("boundCountThirty");
		cellMsg.add("boundCountNinety");
		cellMsg.add("noStorageCount");
		cellMsg.add("noStorageCountThirty");
		cellMsg.add("noStorageCountNinety");
		cellMsg.add("thirtyMonthCount");
		cellMsg.add("ninetyMonthCount");
		cellMsg.add("itemStr");
		for(int i=30;i>0;i--){
			cellMsg.add("dateNum"+i);
		}
		return cellMsg;

	}

	//设置表头信息
	public static Map<String,List<String>> setheadMsg() {
		Map<String,List<String>> headMsg = new HashMap<>();
		//设置一级表头
		List<String> headerMsg1 = new ArrayList<>();
		headerMsg1.add("店铺信息");
		headerMsg1.add("");
		headerMsg1.add("");
		headerMsg1.add("商品基础信息");
		headerMsg1.add("");
		headerMsg1.add("");
		headerMsg1.add("");
		headerMsg1.add("");
		headerMsg1.add("");
		headerMsg1.add("商品运营信息");
		headerMsg1.add("");
		//headerMsg1.add("");
		//headerMsg1.add("");
		headerMsg1.add("亚马逊库存");
		headerMsg1.add("");
		headerMsg1.add("");
		headerMsg1.add("在途库存");
		headerMsg1.add("");
		headerMsg1.add("");
		headerMsg1.add("仓储库存");
		headerMsg1.add("");
		headerMsg1.add("");
		headerMsg1.add("采购库存");
		headerMsg1.add("");
		headerMsg1.add("");
		headerMsg1.add("近30天月销量");
		headerMsg1.add("近90天月销量");
		headerMsg1.add("项目");
		headerMsg1.add("近30天运营数据");
		headMsg.put("headerMsg1",headerMsg1);

		//二级表头
		List<String> headerMsg2 = new ArrayList<>();
		headerMsg2.add("店铺名");
		headerMsg2.add("运营公司简称");
		headerMsg2.add("运营人");
		headerMsg2.add("图片");
		headerMsg2.add("商品编码");
		headerMsg2.add("商品名称");
		headerMsg2.add("SKU");
		headerMsg2.add("ASIN");
		headerMsg2.add("FNSKU");
		//headerMsg2.add("评论");
		//headerMsg2.add("评分");
		headerMsg2.add("购买赢得率");
		headerMsg2.add("转化率");
		headerMsg2.add("数量");
		headerMsg2.add("30天库存系数(数量/月销量)");
		headerMsg2.add("90天库存系数(数量/月销量)");
		headerMsg2.add("数量");
		headerMsg2.add("30天库存系数(数量/月销量)");
		headerMsg2.add("90天库存系数(数量/月销量)");
		headerMsg2.add("数量");
		headerMsg2.add("30天库存系数(数量/月销量)");
		headerMsg2.add("90天库存系数(数量/月销量)");
		headerMsg2.add("数量");
		headerMsg2.add("30天库存系数(数量/月销量)");
		headerMsg2.add("90天库存系数(数量/月销量)");
		headerMsg2.add("");
		headerMsg2.add("");
		headerMsg2.add("");
		//获取最近30天信息,填入二级表头
		List<HashMap<String, String>>  dateList = getAgoDay();
		for(int i=0;i<dateList.size();i++){
			String dateTime = dateList.get(i).get("dateTime");
			String[] dateStr = dateTime.split("-");
			headerMsg2.add(dateStr[1]+'月'+dateStr[2]+'日');
		}
		headMsg.put("headerMsg2",headerMsg2);
		return headMsg;
	}



	//获取过去30天的日期集合
	public static List<HashMap<String, String>> getAgoDay() {
		List<HashMap<String, String>> dateList = new ArrayList();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = null;
		for(int i=30;i>0;i--){
			HashMap<String,String> msg = new HashMap();
			calendar=Calendar.getInstance();
			calendar.add(Calendar.DAY_OF_MONTH, -i);
			String agoDay = sdf.format(calendar.getTime());
			msg.put("dateTime",agoDay);
			msg.put("dateNum","dateNum"+i);
			dateList.add(msg);
		}
		return dateList;
	}

	/*
	 * 获取统计数据
	 */
	@PostMapping("/getTotalCountByAnalysis")
	@ResponseBody
	public JSONObject getTotalCountByAnalysis(Model model, HttpServletRequest request, HttpServletResponse response
			,@ModelAttribute TpAmazonShopProduct cond,String conditions
	){

		JSONObject result = new JSONObject();
		try {
			//Predicate<String> isNotNull = str-> str!=null && !str.equals("");//非空
			Function<String,String> isNotNull = str -> (str!=null && !str.equals("")) ? str : null ;//非空判断,返回对应的值
			Function<Object,String> isNullRes = str -> (str!=null && !str.toString().equals("")) ? str.toString() : "0" ;//非空判断,返回对应的值

			String shopName = isNotNull.apply(ConditionUtil.getConditionValue(conditions, "B.ShopName"));//店铺名
			String companyName = isNotNull.apply(ConditionUtil.getConditionValue(conditions, "B.VGsJc"));//运营公司简称
			String productCode = isNotNull.apply(ConditionUtil.getConditionValue(conditions, "A.Code"));//商品编码
			String productName = isNotNull.apply(ConditionUtil.getConditionValue(conditions, "B.ProductName"));//商品名称
            String userName = isNotNull.apply(ConditionUtil.getConditionValue(conditions, "B.UserName"));//运营人
            String sku = isNotNull.apply(ConditionUtil.getConditionValue(conditions, "A.SellerSku"));//SKU
            String asin = isNotNull.apply(ConditionUtil.getConditionValue(conditions, "A.Asin"));//Asin
            String fnsku = isNotNull.apply(ConditionUtil.getConditionValue(conditions, "A.FnSku"));//FNSKU


            Map<String, Object> searchInfo = new HashMap<>();
            searchInfo.put("shopName",shopName);
            searchInfo.put("companyName",companyName);
            searchInfo.put("productCode",productCode);
            searchInfo.put("productName",productName);
            searchInfo.put("userName",userName);
            searchInfo.put("sku",sku);
            searchInfo.put("asin",asin);
            searchInfo.put("fnsku",fnsku);

			//查询店铺跟踪表的合计数据
			List<Map<String, Object>> totalCountByAnalysisList = tpAmazonAnalysisService.getTotalCountByAnalysis(searchInfo);
			searchInfo.put("dayNum",90);
            List<Map<String, Object>> ninetyMonthCountList = tpAmazonAnalysisService.getAnalysisTotalCountByOrderDaily(searchInfo);
			searchInfo.put("dayNum",30);
			List<Map<String, Object>> thirtyMonthCountList = tpAmazonAnalysisService.getAnalysisTotalCountByOrderDaily(searchInfo);
			List<Map<String, Object>> productNumAllTotal = tpAmazonAnalysisService.searchStockControlByCodeTotal(searchInfo);
			List<Map<String, Object>> noStorageTotal = tpAmazonAnalysisService.searchNoStorageCountByShopCodeTotal(searchInfo);

			//亚马逊库存数量、在途库存数量
			if(totalCountByAnalysisList!=null && totalCountByAnalysisList.size()>0){
				result.put("fulfillableQuantityTotal",isNullRes.apply(totalCountByAnalysisList.get(0).get("fulfillableQuantity")));
				//result.put("inboundWorkingQuantityTotal",isNullRes.apply(totalCountByAnalysisList.get(0).get("inboundWorkingQuantity")));
				//在途库存=入库数量+预留数量
				int wayNum = (int)totalCountByAnalysisList.get(0).get("inboundWorkingQuantity") + (int)totalCountByAnalysisList.get(0).get("reservedQuantity");
                //在途库存=入库数量
                //int wayNum = (int)totalCountByAnalysisList.get(0).get("inboundWorkingQuantity");
                result.put("wayNumTotal",wayNum);
			}else {
				result.put("fulfillableQuantityTotal",0);
				result.put("wayNumTotal",0);
				//result.put("inboundWorkingQuantityTotal",0);
			}
			//仓储库存数量
			if(productNumAllTotal!=null && productNumAllTotal.size()>0){
				result.put("inboundWorkingQuantityTotal",isNullRes.apply(productNumAllTotal.get(0).get("productNumAll")));
			}else {
				result.put("inboundWorkingQuantityTotal",0);
			}

			//近90天
			if(ninetyMonthCountList!=null && ninetyMonthCountList.size()>0){
				float monthlySales = ((int)ninetyMonthCountList.get(0).get("monthlySales"))/3;
				result.put("ninetyMonthCountTotal",String.format("%.0f", monthlySales));
			}else {
				result.put("ninetyMonthCountTotal",0);
			}
			//近30天
			if(thirtyMonthCountList!=null && thirtyMonthCountList.size()>0){
				result.put("thirtyMonthCountTotal",thirtyMonthCountList.get(0).get("monthlySales"));
			}else {
				result.put("thirtyMonthCountTotal",0);
			}


			//采购
			if(noStorageTotal!=null && noStorageTotal.size()>0){
				result.put("noStorageTotal",isNullRes.apply(noStorageTotal.get(0).get("noStorageCount")));
			}else {
				result.put("noStorageTotal",0);
			}

			result.put("code",0);

		}catch (Exception e){
			logger.error("运营跟踪表-->获取统计数据出错：",e.getMessage(),e);
			result.put("code",-1);
			result.put("msg","获取统计数据失败，请稍后重试！");
		}
		return result;
	}

}



